<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { Edit, Search, Delete } from '@element-plus/icons-vue'
import { type UserDto, type OrgNode, type Role, type Org } from '@/api/sys'
import {
  getUserPage,
  getOrgList,
  getOrgTree,
  getRoleList,
  addUser,
  updateUser,
  deleteUser,
  resetPWD,
  userbindRole,
  userbindOrg,
  getUserBoundOrg,
  getUserBoundRole,
} from '@/api/sys'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'

defineOptions({
  name:"User"
})

const searchDto = reactive({
  username: '',
  orgId: '',
  pageNum: 1,
  pageSize: 10,
})

const isAddDialog = ref(true) // 是否为添加模式
const showDialog = ref(false) // 是否显示模态框
const dialogForm = reactive<UserDto>({
  userId: '',
  username: '',
  password: '',
  status: 1,
  isOnline: 1,
  accountLv: 1,
  orgId: '',
  extend: {
    nickname: '',
    email: '',
    cityCode: '',
  },
  creator: '',
  creatorId: '',
  createdAt: '',
  orgName: '',
})
const selectRoleList = ref<string[]>([]) // 模态框中选中的角色，点击提交时将其转换为 表单参数

const tableData = ref<UserDto[]>([])
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1,
})

const orgTree = ref<OrgNode[]>([])
const orgList = ref<Org[]>([])
const roleList = ref<Role[]>([])

onMounted(() => {
  clickSearchBtn()
  getOrgList().then((res) => {
    orgList.value = res
  })
  getOrgTree().then((res) => {
    orgTree.value = res
  })
  getRoleList().then((res) => {
    roleList.value = res
  })
})

const clickSearchBtn = () => {
  pagination.currentPage = 1
  getUserPage(searchDto).then((res) => {
    tableData.value = res.list
    pagination.total = res.total
  })
}
const clickAddBtn = () => {
  dialogForm.status = 1
  dialogForm.accountLv = 3
  isAddDialog.value = true
  showDialog.value = true
}
const clickEditBtn = (row: UserDto) => {
  dialogForm.userId = row.userId
  dialogForm.status = row.status
  dialogForm.accountLv = row.accountLv
  dialogForm.orgId = row.orgId
  dialogForm.extend.nickname = row.extend.nickname
  dialogForm.extend.email = row.extend.email
  dialogForm.extend.cityCode = row.extend.cityCode
  isAddDialog.value = false
  showDialog.value = true
}
const clickDelBtn = (id: string) => {
  deleteUser(id).then(() => {
    clickSearchBtn()
  })
}
const clickSubDialogForm = () => {
  if (isAddDialog.value) {
    addUser({
      username: dialogForm.username,
      password: dialogForm.password,
      status: dialogForm.status,
      accountLv: dialogForm.accountLv,
      orgId: dialogForm.orgId,
      nickname: dialogForm.extend.nickname,
      email: dialogForm.extend.email,
      cityCode: dialogForm.extend.cityCode,
      roleIds: selectRoleList.value,
    }).then(() => {
      clickSearchBtn()
      showDialog.value = false
    })
  } else {
    updateUser({
      userId: dialogForm.userId,
      status: dialogForm.status,
      accountLv: dialogForm.accountLv,
      orgId: dialogForm.orgId,
      nickname: dialogForm.extend.nickname,
      email: dialogForm.extend.email,
      cityCode: dialogForm.extend.cityCode,
    }).then(() => {
      clickSearchBtn()
      showDialog.value = false
    })
  }
}

const clickResetBtn = (id: string) => {
  ElMessageBox.confirm('该操作会将用户密码重置为默认值，确认操作?', '警告', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      resetPWD(id).then(() => {
        ElMessage({
          type: 'success',
          message: '重置成功！',
        })
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作！',
      })
    })
}

const isBindRole = ref(true)
const showBindDialog = ref(false)
const currUserId = ref<string>('')
interface Option {
  key: string
  label: string
}
const bindOptions = ref<Option[]>([])
const bindIds = ref<string[]>([])
// const filterMethod = (query, item) => {
//   return item.initial.toLowerCase().includes(query.toLowerCase())
// }
const clickBindRoleBtn = (id: string) => {
  currUserId.value = id
  bindOptions.value = []
  getRoleList().then((res) => {
    res.forEach((item) => {
      bindOptions.value.push({
        key: item.roleId,
        label: item.roleName,
      })
    })
    showBindDialog.value = true
    isBindRole.value = true
  })
  getUserBoundRole(id).then((res) => {
    bindIds.value = res
  })
}
const clickBindOrgBtn = (id: string) => {
  currUserId.value = id
  bindOptions.value = []
  getOrgList().then((res) => {
    res.forEach((item) => {
      bindOptions.value.push({
        key: item.id,
        label: item.orgName,
      })
    })
    showBindDialog.value = true
    isBindRole.value = false
  })
  getUserBoundOrg(id).then((res) => {
    bindIds.value = res
  })
}
const clickSubBindDialogForm = () => {
  if (isBindRole.value) {
    const data = { userId: currUserId.value, roleIds: bindIds.value }
    userbindRole(data)
  } else {
    const data = { userId: currUserId.value, orgIds: bindIds.value }
    userbindOrg(data)
  }
  showBindDialog.value = false
}
</script>

<template>
  <div>
    <el-dialog v-model="showBindDialog" :title="isBindRole ? '绑定角色' : '绑定部门'" width="600">
      <el-transfer
        v-model="bindIds"
        filterable
        filter-placeholder="按名称过滤"
        :data="bindOptions"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="clickSubBindDialogForm"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="showDialog"
      :title="isAddDialog ? '添加用户信息' : '更新用户信息'"
      width="500"
    >
      <el-form :model="dialogForm" label-width="auto" style="max-width: 600px">
        <el-form-item label="账户" v-show="isAddDialog">
          <el-input v-model="dialogForm.username" />
        </el-form-item>
        <el-form-item label="密码" v-show="isAddDialog">
          <el-input v-model="dialogForm.password" />
        </el-form-item>

        <el-form-item label="昵称">
          <el-input v-model="dialogForm.extend.nickname" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="dialogForm.extend.email" />
        </el-form-item>
        <el-form-item label="行政编码">
          <el-input v-model="dialogForm.extend.cityCode" />
        </el-form-item>
        <el-form-item label="部门">
          <el-tree-select
            v-model="dialogForm.orgId"
            :data="orgTree"
            check-strictly
            :render-after-expand="false"
            placeholder="请选择部门"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="dialogForm.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账号级别">
          <el-radio-group v-model="dialogForm.accountLv">
            <el-radio :value="1">超级管理员</el-radio>
            <el-radio :value="2">管理员</el-radio>
            <el-radio :value="3">用户</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="角色" v-show="isAddDialog">
          <el-checkbox-group v-model="selectRoleList">
            <el-checkbox
              :value="item.roleId"
              name="role"
              v-for="item in roleList"
              :key="item.roleId"
              >{{ item.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="clickSubDialogForm"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-row>
      <el-col>
        <el-card>
          <el-row class="mb-5">
            <el-col>
              <el-input
                v-model="searchDto.username"
                class="max-w-xs mr-5"
                style="width: 200px"
                placeholder="请输入用户名"
                clearable
              />
              <el-select
                v-model="searchDto.orgId"
                filterable
                placeholder="按部门过滤"
                clearable
                class="width mr-5"
              >
                <el-option
                  v-for="item in orgList"
                  :key="item.id"
                  :label="item.orgName"
                  :value="item.id"
                />
              </el-select>
              <el-button type="primary" :icon="Search" @click="clickSearchBtn">查询</el-button>
              <el-button type="primary" :icon="Search" @click="clickAddBtn">添加用户</el-button>
            </el-col>
          </el-row>
          <el-table :data="tableData" stripe style="width: 100%" show-overflow-tooltip>
            <el-table-column type="index" width="50" label="#" />
            <el-table-column prop="username" label="用户名" min-width="120" />
            <el-table-column prop="extend.nickname" label="昵称" min-width="120" />
            <el-table-column prop="orgName" label="部门" min-width="80" />
            <el-table-column prop="status" label="状态" min-width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status ? 'success' : 'info'">{{
                  scope.row.status ? '可用' : '禁用'
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="accountLv" label="账户级别" min-width="100">
              <template #default="scope">
                <el-tag type="danger" v-if="scope.row.accountLv == 1">超级管理员</el-tag>
                <el-tag type="success" v-if="scope.row.accountLv == 2">管理员</el-tag>
                <el-tag type="primary" v-if="scope.row.accountLv == 3">用户</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="extend.email" label="邮箱" />
            <el-table-column prop="createdAt" label="创建时间" min-width="180">
              <template #default="scope">
                {{ dayjs(new Date(scope.row.createdAt * 1000)).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="180">
              <template #default="scope">
                <el-link :icon="Edit" class="mr-3" type="primary" @click="clickEditBtn(scope.row)"
                  >修改</el-link
                >
                <el-link
                  :icon="Delete"
                  class="mr-3"
                  type="primary"
                  @click="clickDelBtn(scope.row.userId)"
                  >删除</el-link
                >
                <el-dropdown>
                  <el-link type="primary">
                    更多<el-icon><ArrowDown /></el-icon>
                  </el-link>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="clickResetBtn(scope.row.userId)"
                        >重置密码</el-dropdown-item
                      >
                      <el-dropdown-item @click="clickBindOrgBtn(scope.row.userId)"
                        >分配部门</el-dropdown-item
                      >
                      <el-dropdown-item @click="clickBindRoleBtn(scope.row.userId)"
                        >分配角色</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="mt-5"
            layout="prev, pager, next"
            :hide-on-single-page="pagination.total / pagination.pageSize < 2"
            :total="pagination.total"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.width {
  width: 200px;
}
.el-dropdown {
  display: contents;
}
</style>
